package com.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;

public class AxisPanel extends HorizontalPanel {

	public CheckBox cbOnlyDate;
	public TagsPanel tpTags = null;
	private AxisPanel pair = null;

	protected void onAttach() {
		this.cbOnlyDate = new CheckBox(CNStatsFront.get().constants.onlyDate());
		this.cbOnlyDate.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				if (true == event.getValue()) {
					if (true == pair.cbOnlyDate.getValue())
						pair.cbOnlyDate.setValue(false, true);
					if (null != tpTags) {
						for (int i=0;i<CNStatsFront.get().plSearch.getPageSize();) {
							TagLabel tag = (TagLabel) tpTags.getWidget(i);
							if (true == tag.isVisible())
								clickTag(tag);
							else
								i++;
						}						
					}
				}
				else {
					if (null == tpTags) {
						tpTags = new TagsPanel(CNStatsFront.get().plSearch.getPageSize(), 0, new ClickHandler() {
							public void onClick(ClickEvent event) {
								TagLabel tag = (TagLabel) event.getSource();
								clickTag(tag);
							}
						});
						tpTags.setStyleName("appAxisTags");
						add(tpTags);
					}			
				}
			}
		});
		this.add(cbOnlyDate);
		this.cbOnlyDate.setStyleName("appAxisDate");
		this.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
		super.onAttach();
	}

	public String getAxis() {
		if (true == this.cbOnlyDate.getValue() ||
				(null != this.tpTags &&
						0 == this.tpTags.getTagAmount()))
			return "date";
		return this.tpTags.getTagsText();
	}
	
	public void setPair(AxisPanel pair) {
		this.pair = pair;
	}
	
	public void reset(Boolean onlyDate) {
		this.cbOnlyDate.setValue(onlyDate);
		if (null != this.tpTags)
			this.tpTags.clearTags();
	}
	
	private void clickTag(TagLabel tag) {
		if (true == this.pair.cbOnlyDate.getValue())
			this.pair.cbOnlyDate.setValue(false, true);
		this.tpTags.removeTag(tag);
		this.pair.tpTags.addTag(tag.getText());
		if (0 == this.tpTags.getTagAmount())
			this.cbOnlyDate.setValue(true);
	}
}
